from flask import Blueprint, request, jsonify, session, render_template, redirect, url_for
import requests
from flask_login import login_required, current_user

# 创建蓝图
picture_bp = Blueprint('picture', __name__, url_prefix='/picture')

# 图片素材搜索页面
@picture_bp.route('/')
@login_required
def index():
    return render_template('picture.html', username=current_user.username)

# 搜索图片API
@picture_bp.route('/search', methods=['GET'])
@login_required
def search():
    # 获取搜索参数
    query = request.args.get('q', '')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '20')
    
    if not query:
        return jsonify({'error': '未提供搜索关键词'}), 400
    
    try:
        # 构建API请求URL
        api_key = '49843306-f03a9639c49e95feb17474994'  # Pixabay API Key
        api_url = 'https://pixabay.com/api/'
        
        # 构建请求参数
        params = {
            'key': api_key,
            'q': query,
            'image_type': 'photo',
            'pretty': 'true',
            'page': page,
            'per_page': per_page
        }
        
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }
        
        # 发送请求到Pixabay API
        response = requests.get(api_url, params=params, headers=headers, timeout=10)
        response.raise_for_status()
        
        # 解析JSON响应
        result = response.json()
        return jsonify(result)
    except requests.exceptions.RequestException as e:
        return jsonify({'error': f'API请求失败: {str(e)}'}), 500
    except Exception as e:
        return jsonify({'error': f'处理请求时发生错误: {str(e)}'}), 500 